package com.krtech.wecard.config;

import cn.hutool.extra.servlet.ServletUtil;
import com.krtech.wecard.framework.model.CommRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Objects;

@RestControllerAdvice
@Slf4j
public class CommonResponseDataConfig implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.getMethodAnnotation(IgnoreCommRes.class) == null;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (
                Objects.equals(serverHttpRequest.getURI().getPath(), "/oauth/token") ||
                        Objects.equals(serverHttpRequest.getURI().getPath(), "/v2/api-docs") ||
                        Objects.equals(serverHttpRequest.getURI().getPath(), "/swagger-resources") ||
                        serverHttpRequest.getURI().getPath().startsWith("/oauth2") ||
                        serverHttpRequest.getURI().getPath().startsWith("/wx/menu/") ||
                        Objects.equals(serverHttpRequest.getURI().getPath(), "/sys/weixin/publicNumberFocus")
        ) {
            return o;
        }
        if (o instanceof String || o instanceof CommRes || o instanceof ResponseEntity) {
            return o;
        }
        if (o instanceof File) {
            File file = (File) o;
            return returnFile(file);
        }
        return CommRes.ok(o);
    }

    private ResponseEntity<byte[]> returnFile(File file) {
        if (file.exists()) {
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            ServletUtil.write(response, file);
            return null;
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}
